package com.zh.baselibrary.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment <P extends BasePresenter> extends RxFragment  implements BaseView {
    Unbinder unbinder;
    protected P mPresenter;
    protected View cacheView;   //viewpager 中不用重复绘制，有网络请求也不要重复请求
    private boolean isFirst = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(cacheView==null){
            cacheView = inflater.inflate(getLayoutId(), container, false);
        }
        unbinder = ButterKnife.bind(this, cacheView);
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.attachModelView( this, getContext());
        }
        return cacheView;

    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if( isFirst){
            isFirst = false;
            init();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        if ( cacheView != null ) {
            ((ViewGroup) cacheView.getParent()).removeView(cacheView); //从父容器中移除，避免重复添加
        }
        if (mPresenter != null) {
            mPresenter.onDetach();
        }
    }

    protected abstract int getLayoutId();
    protected abstract void init();
    /**
     * 使用MVP模式时需要重写该方法
     */
    protected abstract  P createPresenter();

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return bindUntilEvent(FragmentEvent.STOP);
    }

    @Override
    public void onSuccess(Object object) {

    }

    @Override
    public void onHint(String hint) {
    }
}
